package org.lib.postgresqlhello.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.annotation.MapperScans;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;

/**
 * 数据源2
 * @author zhangluo
 * @date 2021-11-04
 */
//@Configuration
//@MapperScans({
////	@MapperScan(value="org.lib.postgresqlhello.user", sqlSessionFactoryRef = DataSource2Config.DS_TAG + "SqlSessionFactory"),
//	@MapperScan(value="org.lib.postgresqlhello.device", sqlSessionFactoryRef = DataSource2Config.DS_TAG + "SqlSessionFactory")
//})
public class DataSource2Config {
	
	// 关键更改信息！
	public static final String DS_TAG = "lib2";
	public static final String DS_CONFIG_PREFIX = "spring.datasource.two";
	
	public static final String DS_NAME = DS_TAG + "DataSource";
	public static final String DS_SSF = DS_TAG + "SqlSessionFactory";
	public static final String DS_SSTLT = DS_TAG + "SqlSessionTemplate";

	@Primary
	@Bean(DS_NAME)
	@ConfigurationProperties(prefix = DS_CONFIG_PREFIX)
	public DataSource dataSource() {
		return DataSourceBuilder.create().build();
	}
	
	@Primary
	@Bean(DS_SSF)
	public SqlSessionFactory sqlSessionFactory(@Qualifier(DS_NAME) DataSource dataSource) throws Exception {
		// 异常：org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):
//		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		// 正常
		MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		
		// 实践：下面的不一定要配置，，配置后可以在XML中写实现
		// mapper的xml形式文件位置必须要配置，不然将报错
		bean.setMapperLocations(new PathMatchingResourcePatternResolver()
				.getResources("classpath*:/mapper/" + DS_TAG + "/*.xml"));
		
		return bean.getObject();
	}
	
	@Primary
	@Bean(DS_SSTLT)
	public SqlSessionTemplate sqlSessionTemplate(@Qualifier(DS_SSF) SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}
